/**
 * 
 */
package com.mc.wordpdf;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.UUID;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

import com.alibaba.fastjson.JSON;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.ImageRenderInfo;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.RenderListener;
import com.itextpdf.text.pdf.parser.TextRenderInfo;
import com.mc.parameter.Parameter;

/**
 * 
 * 向PDF添加图片
 * 
 * @author w.weizhen
 *
 */
public class PdfDrawImage {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//org.apache.pdfbox 实现在指定位置插入图片
		//问题难点:不能确定准确位置
		pdfboxDrawImage();
		
		//itextpdf 实现
		itextpdfDrawImage();
	}
	
	//当前模块,数据和文件存放路径
	private static final String path = Parameter.data_path + "poitl" + File.separator;
	private static final String pdfName = "OBRN17614226187300.pdf";
	private static final String imgName = "t01f7dd6dc4cde128ed.jpg";
	
	/**
	 * org.apache.pdfbox 实现在指定位置插入图片
	 * 问题难点:不能确定准确位置
	 */
	private static void pdfboxDrawImage()
	{
		try {
			File file = new File(path + pdfName);
	        PDDocument doc = PDDocument.load(file);
	        PDPage myPage = doc.getPage(0);
	        PDImageXObject pdImage = PDImageXObject.createFromFile(path + imgName, doc);
	        //位置
	        float offset_x = 30f;
	        float offset_y = 30f;
	        //计算长宽,避免图片过大
	        BigDecimal max_width = BigDecimal.valueOf(100);
            BigDecimal width = BigDecimal.valueOf(pdImage.getWidth());
            BigDecimal height = BigDecimal.valueOf(pdImage.getHeight());
            BigDecimal ratio = width.divide(max_width, 3, BigDecimal.ROUND_UP);
	        try (PDPageContentStream cont = new PDPageContentStream(doc, myPage, PDPageContentStream.AppendMode.APPEND, false, false)) {
	            cont.drawImage(pdImage, offset_x, offset_y, max_width.intValue(), height.divide(ratio, 3, BigDecimal.ROUND_UP).intValue());
	        }
	        String new_pdf = path + UUID.randomUUID().toString().replaceAll("-", "") + ".pdf";
	        doc.save(new_pdf);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
    
	/**
	 * itextpdf 实现
	 */
	private static void itextpdfDrawImage()
	{
		try {
			
			
			
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}